package crash.box;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class GameView extends SurfaceView implements Callback {
	private GameThread mThread;					
	private GameThread thread;
	private SurfaceHolder mSurfaceHolder;		// SurfaceHolder 
	private int Width, Height;					
	private int running = 1;
	private int game_play = 1;
	private Random rand;

    private Bitmap top_bg, game_ready_bg, game_bg2; 

	private int box_count = 30;		// Number of Box 
	private int box_red_count = 10;
	private Bitmap []box_img = new Bitmap[box_count];	// Box Image
	private Bitmap []box_red = new Bitmap[box_red_count];
	private int[] rand_x = new int[box_count];			// Box X 占쏙옙표
	private int[] rand_y = new int[box_count];			// Box Y 占쏙옙표

	// Returned Values from Option Activity 
	static int p_mode_ab = 1;		// Return Value for [ Game Mode A/B ]
	static int p_vib_onoff = 1;		// Return Value for [ Vibration On/Off ] 0: Off / 1: On
	static int p_sound = 0;			// Return Value for [ Sound ] 0: Off / 1: On

	private ScoreDAO m_dao   = null;            /* R_Rank DAO   */
	private Paint mTextPaint = new Paint();
	private int sec = 60;
	private int ingame = 0;
	private int count = 0;
	private int box_size_x = 0;
	private int box_size_y = 0;


	private Timer timer = new Timer();
	private int timer_lock = 1;
	private int touch_lock = 0;

	private int score = 0;
	
	// Sound Effect
	private SoundPool Sp_shot = null;
	private int Sound_shot;

	// Vibration Effect
	private Vibrator vib = null;
	private Context mContext;
	private AlertDialog.Builder builder;
	private EditText edit;
	private Button btn;
	private String playername;
	private LayoutInflater inflater;
	private View layout;

	// Constructor
	public GameView(Context context) {
		super(context);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);

		Display display = ((WindowManager)context.getSystemService(context.WINDOW_SERVICE)).getDefaultDisplay();
		Width  = display.getWidth();
		Height = display.getHeight();


		Resources res = context.getResources();

		game_ready_bg = BitmapFactory.decodeResource(res, R.drawable.game_ready_bg);
		game_ready_bg = Bitmap.createScaledBitmap(game_ready_bg, Width, Height, true);
		
		game_bg2 = BitmapFactory.decodeResource(res, R.drawable.game_bg);
		game_bg2 = Bitmap.createScaledBitmap(game_bg2, Width, Height, true);

		for(int i = 0; i < box_count; i++){
			box_img[i] = BitmapFactory.decodeResource(res, R.drawable.box);
			box_img[i] = Bitmap.createScaledBitmap(box_img[i], 60, 60, true);
		}
		
		for(int i = 0; i< box_red_count; i++){
			box_red[i] = BitmapFactory.decodeResource(res, R.drawable.box_red);
			box_red[i] = Bitmap.createScaledBitmap(box_red[i], 60, 60, true);
		}
		
		// Sound Effect Setting
		Sp_shot = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
		Sound_shot = Sp_shot.load(getContext(), R.raw.shot, 1);

		// Vibration Effect Setting
		vib = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
		
		mThread = new GameThread(context, holder);

		box_size_x = box_img[0].getHeight() - box_img[0].getHeight()/5;
		box_size_y = box_img[0].getWidth() - box_img[0].getWidth() /5;

        try{
        	m_dao = ScoreDAO.GetInstance((Activity) context);
        }catch(Exception e){
        	e.printStackTrace();
        } 
        
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    layout = inflater.inflate(R.layout.dialog, null);
        builder = new AlertDialog.Builder(mContext);
    	Dialog();
	}

	public void surfaceCreated(SurfaceHolder arg0) {
		try {
			mThread.start();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
	}

	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean done = true;
		while (done) {
			mThread.stop();			
			done = false; 
		}
	}

	class GameThread extends Thread {
		SurfaceHolder  mHolder;

		public GameThread(Context context, SurfaceHolder holder) {
			mHolder = holder;
			mContext = context;
		}

		//--------------------------------------	
		//    Thread run
		//--------------------------------------
		public void run() {
			while (running == 1) {
				Canvas canvas = mHolder.lockCanvas();
				try {
					synchronized (mHolder) {
						
						if(ingame == 0){
							canvas.drawBitmap(game_ready_bg, 0, 0, null);	
							}
						
						if(ingame == 1){
							if(timer_lock == 1){
								showTimer();
							}
							startGame(canvas);
												
							if(sec == 0){
								builder.show();
								ingame= 2;
							}
							
							if(sec % 5 == 0){
								game_play = 1;
							}
							timer_lock = 2;
						}
						
						if(ingame == 2){
							canvas.drawBitmap(game_bg2, 0, 0, null);
						}
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					if(canvas != null)
					mHolder.unlockCanvasAndPost(canvas);
				} 
			}
			
		}
	}
  
	private TimerTask myTask;
	
	public void showTimer(){
		myTask = new TimerTask() {
			public void run() {
				sec--;
				if(sec == 0){
					myTask.cancel();
				}
			}
		};
		timer.schedule(myTask, 0, 1000);
	}
	
	private int[] rand_red_x = new int[box_red_count];
	private int[] rand_red_y = new int[box_red_count];
	
	public void startGame(Canvas can){
		mTextPaint.setAntiAlias(true);
		mTextPaint.setColor(Color.BLACK);
		mTextPaint.setTextSize(20);

		can.drawBitmap(game_bg2, 0, 0, null);
		can.drawText("Timer : " + sec + "  Score :  " + count, 15 , 15 , mTextPaint);
		if(game_play == 1){
			for(int i = 0; i < box_count; i++){
				rand_x[i] = (int)(Math.random()*(Width - 50));
				rand_y[i] = 50 + (int)(Math.random()*(Height - 100));
			}
			
			for(int i =0; i<box_red_count; i++){
				rand_red_x[i] = (int)(Math.random()*(Width - 50));
				rand_red_y[i] = 50 + (int)(Math.random()*(Height - 100));
			}
			game_play = 0;
		}

		for(int i = 0; i < box_count; i++){
			can.drawBitmap(box_img[i], rand_x[i], rand_y[i], null);
		}
		
		for(int i = 0; i<box_red_count; i++){
			can.drawBitmap(box_red[i], rand_red_x[i], rand_red_y[i], null);
		}
	}
	



	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);

		if(event.getAction() == MotionEvent.ACTION_DOWN)
		{
			if(ingame == 0){
				ingame = 1;
				sec = 30;
			}

			// Game Start
			if(ingame == 1){
				int tx = (int)event.getX();		
				int ty = (int)event.getY();		
				for(int i = box_count-1; i >=0; i--){
					if( (tx > rand_x[i]) &&
							(tx < rand_x[i] + box_size_x) && 
							(ty > rand_y[i]) &&
							(ty < rand_y[i] + box_size_y) &&						
							(touch_lock == 0)){

						rand_x[i] = - 300;
						rand_y[i] = - 300;
						
						count++;
						touch_lock = 1;
						
						// Sound Effect
						if (p_sound == 1)
							Sp_shot.play(Sound_shot, 1f, 1f, 0, 0, 1f);
						
						// Vibration Effect
						if (p_vib_onoff == 1)
							vib.vibrate(100);
						
						if(sec == 0){
							builder.show();
							ingame = 2;

						}
						
						/*
						// Game End
						if(count == box_count) 
							gameEnd();
						*/
										
					}
				}
			}
			if(ingame == 1){
				int tx = (int)event.getX();		
				int ty = (int)event.getY();		
				for(int i = box_red_count-1; i>=0; i--){
					if( (tx > rand_red_x[i]) &&
						(tx < rand_red_x[i] + box_size_x) && 
						(ty > rand_red_y[i]) &&
						(ty < rand_red_y[i] + box_size_y) &&						
						(touch_lock == 0)){
						
						myTask.cancel();
						ingame = 2;
						builder.show();
						
					}
				}
			}
		}
		touch_lock = 0;
		return true;
	}

	public void Dialog() 
	{
	    edit =(EditText) layout.findViewById(R.id.dia_edit);       
	    builder.setView(layout);
	    builder.setTitle("이름을 입력하세요.");
	    builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
     	   public void onClick(DialogInterface dialog, int id) { 
     		    playername = edit.getText().toString();
     		    gameEnd();
    		   } 
    	   });
	    builder.create();
	}
	
	public void gameEnd(){
		
		try {
			m_dao.Append(playername, count);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		count = 0;
		running = 0;
	}
}